package com.fqgj.xjd.user.service.impl;
/**
 * Created by zhangxingyun on 17/7/21.
 */

import com.fqgj.common.api.Response;
import com.fqgj.xjd.user.client.*;
import com.fqgj.xjd.user.client.enums.CreditAuthTypeEnum;
import com.fqgj.xjd.user.client.enums.UserAccountTypeEnum;
import com.fqgj.xjd.user.client.enums.UserBindCardTypeEnum;
import com.fqgj.xjd.user.client.enums.UserTypeEnum;
import com.fqgj.xjd.user.client.request.BankAuth;
import com.fqgj.xjd.user.client.request.CookieRequest;
import com.fqgj.xjd.user.client.request.CreditAuthRequest;
import com.fqgj.xjd.user.client.request.CustomerCreditCallbackRequest;
import com.fqgj.xjd.user.client.response.*;
import com.fqgj.xjd.user.common.enums.UserErrorCodeEnum;
import com.fqgj.xjd.user.common.utils.DES;
import com.fqgj.xjd.user.dao.UserAuthCreditKrazybeeCibilDao;
import com.fqgj.xjd.user.dao.UserDao;
import com.fqgj.xjd.user.entity.UserAuthCreditKrazybeeCibilEntity;
import com.fqgj.xjd.user.entity.UserAuthXuexinEntity;
import com.fqgj.xjd.user.service.UserAuthCreditService;
import com.fqgj.xjd.user.service.UserAuthXueXinService;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName:
 * @Description: 用户授权认证服务
 * @Author zhangxingyun
 * @Create 2017-07-21 09:37
 */
@Service("userAuthService")
public class UserAuthServiceImpl implements UserAuthService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserAuthService.class);

    @Autowired
    UserService userService;

    @Autowired
    UserBankService userBankService;

    @Autowired
    UserAuthAccountService userAuthAccountService;

    @Autowired
    UserAuthXueXinService userAuthXueXinService;

    @Autowired
    UserAuthCreditService userAuthCreditService;

//    @Autowired
//    PayAuthService payAuthService;

    @Autowired
    UserDao userDao;

    @Autowired
    private UserAuthCreditKrazybeeCibilDao userAuthCreditKrazybeeCibilDao;

    @Autowired
    private UserAuthKeyPaymentService userAuthKeyPaymentService;

    /**
     * TODO bank
     * 实名认证成功
     * @param creditAuth
     * @return
     */
    @Override
    public Response<Boolean> creditAuth(CreditAuthRequest creditAuth) {
        userAuthCreditService.auth(creditAuth);
        return Response.ok().putData(true);
    }

    /**
     * 根据用户userCode获取用户的实名认证信息
     * @param userCode
     * @return
     */
    @Override
    public Response<CreditAuthResponse> getCreditAuthInfoByUserCode(String userCode) {
        CreditAuthResponse creditAuthResponse = userAuthCreditService.getCreditAuthInfoByUserCode(userCode);
        return Response.ok().putData(creditAuthResponse);
    }

    /**
     * 取消授权
     * @param creditAuth
     * @return
     */
    @Override
    public Response<Boolean> cancelAuth(CreditAuthRequest creditAuth) {
        if (creditAuth.getAuthType().equals(CreditAuthTypeEnum.BANK.getType())) {
            return Response.error("银行卡无法解绑");
        }
        userAuthCreditService.cancelAuth(creditAuth);
        return Response.ok().putData(true);
    }
    /**
     * 绑卡实名
     * @param userCode
     * @return
     */

    private void addUserAuthPayment(String userCode,UserBindCardTypeEnum bindCardTypeEnum){
        UserAuthPayment userAuthPayment = new UserAuthPayment(userCode,userCode,userCode);
        userAuthKeyPaymentService.addUserAuthKey(userAuthPayment, bindCardTypeEnum);
    }
    /**
     * 学信网认证
     * @param userCode
     * @param username
     * @param password
     * @return
     */
    @Override
    public Response<Boolean> userXuexinAuth(String userCode, String username, String password) {
        Response<UserAuthAccount> response = userAuthAccountService.getUserAuthAccountByAccountName(username, UserAccountTypeEnum.XUEXIN);
        UserAuthAccount userAuthAccount = response.getData();
        if (userAuthAccount != null) {
            return Response.error(UserErrorCodeEnum.XUEXIN);
        }
        try {
//            BindResult result = userCreditCrawlerWebservice.crawlXuexinAccount(userId, username, password, appCodeEnum.getCategory());

            BindResult result = new BindResult();
            if ("wrongPassword".equals(result.getMessage())) {
                return Response.error(UserErrorCodeEnum.XUEXIN,"用户名或密码错误，请确认");
            }

            if ("notUserInfo".equals(result.getMessage())) {
                return Response.error(UserErrorCodeEnum.XUEXIN,"您没有学籍信息，请核对！");
            }

            if ("loginFaild".equals(result.getMessage())) {
                return Response.error(UserErrorCodeEnum.XUEXIN,"登录失败，请稍后重试！");
            }

            Response<User> userResponse = userService.getUserByUserCode(userAuthAccount.getUserCode());
            User user = userResponse.getData();


            List<XueXinUserDetails> xxuds = new ArrayList<XueXinUserDetails>();
            if (result.getObj() instanceof List) {
                xxuds = (List<XueXinUserDetails>) result.getObj();
            } else {
                xxuds.add((XueXinUserDetails) result.getObj());
            }

            if (StringUtils.isNotEmpty(user.getIdentityNo())
                    && !user.getIdentityNo().equals(xxuds.get(0).getIdentityNo())) {
                return Response.error(UserErrorCodeEnum.XUEXIN,"与身份证认证信息不一致，请重新认证！");
            }

            userAuthXueXinService.saveUserXueXin(userCode,xxuds,username,password);
            userAuthAccount = new UserAuthAccount();
            userAuthAccount.setAccount(username);
            userAuthAccount.setUserCode(userCode);
            userAuthAccount.setPassWord(password);
            userAuthAccount.setType(UserAccountTypeEnum.XUEXIN.getDesc());
            userAuthAccountService.saveUserAuthAccount(userAuthAccount);
            UserAuthXuexinEntity userAuthXuexinEntity = userAuthXueXinService.selectXueXinByUserCode(userCode);
            if (userAuthXuexinEntity != null) {
                String[] studentStatus = {"保留入学资格", "在校(休学)", "在校(保留学籍)", "在校(报到入学)", "在校(暂缓注册)", "在校(注册学籍)",
                        "在籍(休学)", "在籍(保留学籍)", "在籍(报到入学)", "在籍(暂缓注册)", "在籍(注册学籍)"};
                if (ArrayUtils.contains(studentStatus, userAuthXuexinEntity.getStatus())) {
                    userService.updateUserType(userCode, UserTypeEnum.SUTDENT);
                }else{
                    userService.updateUserType(userCode, UserTypeEnum.ADULT);
                }
            }
            return Response.ok();
        } catch (Exception e) {
            return Response.error(UserErrorCodeEnum.XUEXIN,"绑定失败，请稍后重试！");
        }
    }

    /**
     * 京东认证
     * @param userCode
     * @param username
     * @param password
     * @param verifyCode
     * @return
     */
    @Override
    public Response<String> userJDAuth(String userCode, String username, String password, String verifyCode) {
//        if (StringUtils.isBlank(verifyCode)) {
//            BindResult br = userCreditCrawlerWebservice.crawlJD(userId, username,password, null);
//            if (!br.isSuccessful()) {
//                return Response.error(UserErrorCodeEnum.JD,br.getMessage());
//            } else {
//                if (br.isNeedVerifyCode()) {
//                    return Response.ok().putData("showVerifyCode");
//                } else {
//                    return Response.ok();
//                }
//            }
//        } else {
//            BindResult br = userCreditCrawlerWebservice.crawlJD(userId,username, password,verifyCode);
//            if (br.isSuccessful()) {
//                return Response.ok();
//            } else {
//                return Response.error(UserErrorCodeEnum.JD,br.getMessage());
//            }
//        }
        return Response.error(UserErrorCodeEnum.JD);
    }

    /**
     * 淘宝认证
     * @param userCode
     * @param cookies
     * @return
     */
    @Override
    public Response<String> userTaobaoAuth(String userCode,List<CookieRequest> cookies) {
//        BindResult br = this.userCreditCrawlerWebservice.crawlTaobaoAccount(userId, appCodeEnum.getCategory(), cookies);
//        if (br.isSuccessful()) {
//            return Response.ok();
//        }

        return Response.error(UserErrorCodeEnum.TAOBAO,"认证失败，请稍后再试！");
    }

    /**
     * QQ认证
     * @param userCode
     * @param qq
     * @param password
     * @return
     */
    @Override
    public Response<Boolean> userQQAuth(String userCode, String qq, String password) {
        UserAuthAccount userAuthAccount = new UserAuthAccount();
        userAuthAccount.setAccount(qq);
        userAuthAccount.setUserCode(userCode);
        try {
            userAuthAccount.setPassWord(DES.encrypt(password));
        } catch (Exception e) {
            e.printStackTrace();
        }
        userAuthAccount.setType(UserAccountTypeEnum.QQ.getDesc());
        userAuthAccount.setPassWordStatus(-1);
        userAuthAccountService.saveUserAuthAccount(userAuthAccount);
        return Response.ok().putData(true);
    }

    @Override
    public Response<Boolean> addUserKrazyBeeCrediteReport(CustomerCreditCallbackRequest customerCreditCallbackRequest) {
        if (Objects.isNull(customerCreditCallbackRequest)) {
            return Response.error(UserErrorCodeEnum.AUTH_ERROR, UserErrorCodeEnum.AUTH_ERROR.getMsg());
        }
        Map<String, Object> queryParams = Maps.newHashMap();
        queryParams.put("referenceNumber", customerCreditCallbackRequest.getReferenceNumber());
        List<UserAuthCreditKrazybeeCibilEntity> userCreditList = userAuthCreditKrazybeeCibilDao.selectByParams(queryParams);
        if (CollectionUtils.isNotEmpty(userCreditList)) {
            UserAuthCreditKrazybeeCibilEntity updateBO = userCreditList.get(0);
            BeanUtils.copyProperties(customerCreditCallbackRequest, updateBO);
            userAuthCreditKrazybeeCibilDao.updateByPrimaryKey(updateBO);
        } else {
            UserAuthCreditKrazybeeCibilEntity entity = new UserAuthCreditKrazybeeCibilEntity();
            BeanUtils.copyProperties(customerCreditCallbackRequest, entity);
            userAuthCreditKrazybeeCibilDao.insert(entity);
        }
        return Response.ok();


    }
}
